/**
 * Copyright (c) 2008, George Taylor
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, are permitted 
 * provided that the following conditions are met:
 * 
 *   * Redistributions of source code must retain the above copyright notice, this list of 
 *     conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above copyright notice, this list of 
 *     conditions and the following disclaimer in the documentation and/or other materials 
 *     provided with the distribution.
 *   * Neither the name of the copyright holder's organization nor the names of its contributors 
 *     may be used to endorse or promote products derived from this software without specific 
 *     prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR 
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND 
 * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER 
 * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT 
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package uk.co.taylorconsulting.annoweb.web.controller;

import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;

import uk.co.taylorconsulting.annoweb.web.builder.WebBuilder;
import uk.co.taylorconsulting.annoweb.web.builder.data.Site;

public class WebController extends HttpServlet {
	private WebFramework      framework;
	private ServletConfig     config;
	private static final long serialVersionUID = 9068648708242215669L;
	private static Logger     LOG              = Logger.getLogger(WebController.class);
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		while (framework == null) {
			try {
				synchronized (this) {
					wait(100);
				}
			} catch (Exception e) {}
		}
		String path = request.getServletPath().toUpperCase();
		if (LOG.isDebugEnabled()) {
			LOG.debug("Processing path:" + path);
		}
		framework.process(request, response, request.getSession().getServletContext());
	}
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		while (framework == null) {
			try {
				synchronized (this) {
					wait(100);
				}
			} catch (Exception e) {}
		}
		setParametersToAttributes(request);
		framework.process(request, response, request.getSession().getServletContext());
	}
	
	@SuppressWarnings("unchecked")
	private void setParametersToAttributes(HttpServletRequest request) {
		ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());
		List<FileItem> files = null;
		try {
			files = servletFileUpload.parseRequest(request);
			for (FileItem fi : files) {
				if (fi.isFormField()) {
					request.setAttribute(fi.getFieldName(), fi.getString());
				} else {
					request.setAttribute(fi.getFieldName(), fi);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@Override
	public void init() throws ServletException {}
	
	@Override
	public void init(ServletConfig config) throws ServletException {
		this.config = config;
		Thread t = new Thread(new Runnable() {
			public void run() {
				process();
			}
		});
		t.start();
	}
	
	private void process() {
		HashMap<String, Site> sites = new HashMap<String, Site>();
		String ext = processConfig(sites);
		String classpath = config.getServletContext().getRealPath("/");
		build(classpath, ext, sites);
		output(sites);
	}
	
	private void output(HashMap<String, Site> sites) {
		for (Site s : sites.values()) {
			s.debug();
		}
	}
	
	private String processConfig(HashMap<String, Site> sites) {
		String ext = "do";
		for (Enumeration<?> namesEnum = config.getInitParameterNames(); namesEnum.hasMoreElements();) {
			String name = (String) namesEnum.nextElement();
			if (name.equalsIgnoreCase("extension")) {
				ext = config.getInitParameter(name);
			} else {
				// Must be a context name
				sites.put(name, new Site(name, config.getInitParameter(name)));
			}
		}
		for (Site s : sites.values()) {
			s.setExt(ext);
		}
		return ext;
	}
	
	private void build(String classpath, String ext, HashMap<String, Site> sites) {
		long time = System.currentTimeMillis();
		WebBuilder wb = new WebBuilder();
		wb.process(classpath, ext, sites);
		framework = wb.build(sites, classpath);
		wb = null;
		LOG.info("Site build took " + (System.currentTimeMillis() - time) + " millis seconds.");
	}
}
